//
//  UIButton+ButtonRunTime.m
//  VIVAT
//
//  Created by 韩丛旸 on 16/4/26.
//  Copyright © 2016年 AnBang. All rights reserved.
//

#import "UIButton+ButtonRunTime.h"
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "HYLogger.h"


@implementation UIButton (ButtonRunTime)

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //获得viewController的生命周期方法的selector
        SEL systemSel = @selector(sendAction:to:forEvent:);
        //自己实现的将要被交换的方法的selector
        SEL swizzSel = @selector(hy_sendAction:to:forEvent:);
        //两个方法的Method
        Method systemMethod = class_getInstanceMethod([self class], systemSel);
        Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
        //        //首先动态添加方法，实现是被交换的方法，返回值表示添加成功还是失败
        BOOL isAdd = class_addMethod([self class], systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
        if (isAdd) {
            //如果成功，说明类中不存在这个方法的实现
            //将被交换方法的实现替换到这个并不存在的实现
            class_replaceMethod([self class], swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
        }else{
            //否则，交换两个方法的实现
            method_exchangeImplementations(systemMethod, swizzMethod);
        }
    });
    [super addTarget:target action:action forControlEvents:controlEvents];
}

- (void)hy_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
    UIViewController *vc = (UIViewController *)target;

    if ([HYLogger sharedInstance].isRuntimeLogEffective) {
        HYLogDebug(@"*************UIButton*************\nsender       = %@\nselector     = %s\nsender title = %@\n**********************************", [vc class],sel_getName(action),[self titleForState:UIControlStateNormal]);
    }
    [super sendAction:action to:target forEvent:event];
}

@end
